import React,{useState,useEffect} from 'react';
import { Table, Tag, Button, Modal, Popover,Switch } from 'antd'
import axios from '_axios@0.27.2@axios';
import { EditOutlined,DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
const Rightlist = () => {
  const [dataSource, setdataSource] = useState([])
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
       return <b>{ id }</b>
      }
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => {
       return <Tag color="orange">{ key }</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button danger shape="circle" onClick={() => confirmMethod(item)} icon={<DeleteOutlined />} />
          <Popover content={
            <div style={{ textAlign: 'center' }}>
              <Switch checked={item.pagepermisson} onChange={
                ()=>switchMethod(item)
              }></Switch>
            </div>
          }
            title="页面配置" trigger={item.pagepermisson === undefined?'':'click'}>
            <Button
              type="primary"
              disabled={item.pagepermisson === undefined}
              shape="circle"
              icon={<EditOutlined />}
            />
          </Popover>
       </div>
      }
    },
  ];
  // 开关
  const switchMethod = (item) => {
    item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
    setdataSource([...dataSource])
    if (item.grade === 1) {
      axios.patch(`/rights/${item.id}`, {
        pagepermisson:item.pagepermisson
      })
    } else {
       axios.patch(`/children/${item.id}`, {
        pagepermisson:item.pagepermisson
      })
    }
  }
  // 删除提示
  const confirmMethod = (item) => {
    Modal.confirm({
    title: '删除',
    icon: <ExclamationCircleOutlined />,
    content: '你确认删除吗？',
    okText: '确认',
    cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    })
  }
  // 删除
  const deleteMethod = (item) => {
    if (item.grade === 1) {
      setdataSource(dataSource.filter(data => data.id !== item.id))
      axios.delete(`/rights/${item.id}`)
    } else {
      let list = dataSource.filter(data => data.id === item.rightId)
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      setdataSource([...dataSource])
      axios.delete(`/children/${item.id}`)
    }
  }
  // 初始化
  useEffect(() => {
    axios.get('/rights?_embed=children').then(res => {
      const list = res.data
      list.forEach(item => {
        if (item.children.length === 0) {
          item.children = ''
        }
      })
      setdataSource(list)
    })
  },[])
  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
      />;
    </div>
  );
}

export default Rightlist;
